#include "shipInventory.h"
#include "luaWrapper.h"
#include <QTextStream>
#include <QFile>
#include <QDebug>

ShipInventory::ShipInventory()
{
}

ShipInventory::ShipInventory(const QString& name)
  : mName(name)
{
  QString filename("userdata/ships/"+mName+".lua");
  if (!QFile::exists(filename))
  {
    filename = "userdata/ships/"+mName+".lua";
    if (!QFile::exists(filename))
    {
      qDebug() << "Failed to find " << mName << ".lua in userdata/ships or lua/ships";
      filename = "";
    }
  }

  if (filename.size())
  {
    LuaWrapper lua;
    lua.load(filename);
    lua_getglobal(lua.mLua, "ship");
    if (lua_istable(lua.mLua, -1))
    {
      if (lua.getTableTable(-1, "positionComponents"))
      {
        for(lua.initTableIterator(); lua.nextTableIteration();) //row
        {
          unsigned int row(lua_tointeger(lua.mLua, -2));
          for(lua.initTableIterator(); lua.nextTableIteration();) //col
          {
            unsigned int col(lua_tointeger(lua.mLua, -2));
            addComponent(row, col, lua_tostring(lua.mLua, -1));
          }
        }
      }
      else
      {
        lua.error("could not find positionComponents table");
      }
    }
    else
    {
      lua.error("could not find ship table");
    }
  }
  qDebug() << "Ship " << mName << " successfully loaded";
}

void ShipInventory::addComponent(unsigned int row, unsigned int col,
                                 const QString &componentName)
{
  mPositionComponents[row][col] = componentName;
}

void ShipInventory::removeComponent(unsigned int row, unsigned int col)
{
  mPositionComponents[row].remove(col);
  if(mPositionComponents[row].isEmpty())
  {
    mPositionComponents.remove(row);
  }
}

void ShipInventory::clear()
{
  mPositionComponents.clear();
}

PositionComponentNameMap ShipInventory::positionComponents() const
{
  return mPositionComponents;
}

void ShipInventory::setName(const QString &n)
{
  mName = n;
}

QString ShipInventory::name() const
{
  return mName;
}

void ShipInventory::save()
{
  QFile f("userdata/ships/"+mName+".lua");
  f.open(QIODevice::WriteOnly | QIODevice::Text);
  QTextStream textStream(&f);
  textStream << "ship = {name='" << mName << "'," << endl;
  textStream << "        positionComponents={}}" << endl << endl;
  PositionComponentNameMap::const_iterator rowit(mPositionComponents.begin());
  for(; rowit != mPositionComponents.end(); ++rowit)
  {
    textStream << "ship.positionComponents[" << rowit.key() << "]={}" << endl;
    ColumnComponentNameMap::const_iterator colit(rowit.value().begin());
    for(; colit != rowit.value().end(); ++colit)
    {
      textStream << "ship.positionComponents[" << rowit.key() << "][" << colit.key() << "]='" << colit.value() << "'" << endl;
    }
  }
}
